import dayjs from 'dayjs';
import { getTimeDuration, pick, deepClone, arr2Obj, groupBy } from '../common/utils';
import { ACTIVITY_ACTION, ACTIVITY_USER_ROLE, ACTIVITY_STATUS_VALUE, SALES_TYPE_VALUE, ACTIVITY_OWNER_VALUE, DELIVERY_TYPE_VALUE, FREQUENCY_TYPE } from '../constants/activity';
import { USER_ACTION_TYPE } from '../constants/user';
import { DEFAULT_BG_LIST, ACTIVITY_TYPE } from '../constants/common';

/**
 * 处理默认活动信息
 * @param ownerInfo 拥有者信息
 */
export const dealActivityDefaultData = (ownerInfo = {}) => {
    return {
        name: '',
        type: ACTIVITY_TYPE.group_buying,
        tel: ownerInfo.tel,
        background: DEFAULT_BG_LIST[0],
        intro: [
            { type: 'text', resource: '' }
        ],
        begined: dayjs().startOf('minute').valueOf(),
        ended: dayjs().add(6, 'day').startOf('minute').valueOf(),
        saleMode: SALES_TYPE_VALUE.no_limit,
        maxiumPurchaseFrequency: 0,
        activityProductWithSkus: [],
        consignment: {
            allowHiddenProduct: false,
            allowAllSpokesman: true,
            consignmentBonusSettings: [],
        },
    };
};

/**
 * 处理活动保存数据
 * @param {Object} activityInfo 
 * @param {String} owner // brand | spokesman
 */
export const dealActivitySaveData = (activityInfo, owner = ACTIVITY_OWNER_VALUE.brand) => {
    activityInfo = deepClone(activityInfo);
    if (owner === ACTIVITY_OWNER_VALUE.brand) {
        const { intro, deliveryModes, consignment, saleMode } = activityInfo;
        const { allowAllSpokesman } = consignment;
        // map
        const consignmentBonusSettingsMap = arr2Obj(consignment.consignmentBonusSettings, 'productId');
        // 描述
        activityInfo.intro = intro.filter(i => i.resource);
        // 配送方式
        if (deliveryModes && deliveryModes.indexOf(DELIVERY_TYPE_VALUE.express) === -1) {
            delete activityInfo.unifiedShippingFee;
            delete activityInfo.isUseWarehouseShippingFeeRule;
        }
        // 代言帮卖
        if (allowAllSpokesman) {
            activityInfo.consignment.specificSpokesmanIds = [];
        }
        // 数据格式处理
        activityInfo.minimumPurchaseAmount !== undefined && (activityInfo.minimumPurchaseAmount -= 0);
        activityInfo.maxiumPurchaseFrequency !== undefined && (activityInfo.maxiumPurchaseFrequency -= 0);
        activityInfo.unifiedShippingFee !== undefined && (activityInfo.unifiedShippingFee-= 0);
        activityInfo.consignment.consignmentBonusSettings = activityInfo.activityProductWithSkus.map(i => {
            const obj = {
                productId: i.productId,
                bonusRate: consignmentBonusSettingsMap[i.productId] ? consignmentBonusSettingsMap[i.productId].bonusRate : '',
            };
            obj.bonusRate -= 0;
            return obj;
        });
        activityInfo.activityProductWithSkus = activityInfo.activityProductWithSkus.map(ps => {
            ps.skus = ps.skus.map(s => {
                s.price -= 0;
                s.maximum -= 0;
                return s;
            });
            return ps;
        });
        if (saleMode === SALES_TYPE_VALUE.only_brand_selling) {
            delete activityInfo.consignment;
        }
        // 删除数据
        delete activityInfo.activityId;
        delete activityInfo.brandId;
        delete activityInfo.pubUserId;
        delete activityInfo.qualifyTypes;
        delete activityInfo.processStatus;
        delete activityInfo.published;
        delete activityInfo.verifyQualification;
        delete activityInfo.owner;
        delete activityInfo.pics;
    } else if (owner === ACTIVITY_OWNER_VALUE.store) {
        const { intro, consignment, saleMode } = activityInfo;
        const { allowAllSpokesman } = consignment;
        // map
        const consignmentBonusSettingsMap = arr2Obj(consignment.consignmentBonusSettings, 'productId');
        // 描述
        activityInfo.intro = intro.filter(i => i.resource);
        // 代言帮卖
        if (allowAllSpokesman) {
            activityInfo.consignment.specificSpokesmanIds = [];
        }
        // 数据格式处理
        activityInfo.minimumPurchaseAmount !== undefined && (activityInfo.minimumPurchaseAmount -= 0);
        activityInfo.maxiumPurchaseFrequency !== undefined && (activityInfo.maxiumPurchaseFrequency -= 0);
        activityInfo.consignment.consignmentBonusSettings = activityInfo.activityProductWithSkus.map(i => {
            const obj = {
                productId: i.productId,
                bonusRate: consignmentBonusSettingsMap[i.productId] ? consignmentBonusSettingsMap[i.productId].bonusRate : '',
            };
            obj.bonusRate -= 0;
            return obj;
        });
        activityInfo.activityProductWithSkus = activityInfo.activityProductWithSkus.map(ps => {
            ps.skus = ps.skus.map(s => {
                s.price -= 0;
                s.maximum -= 0;
                return s;
            });
            return ps;
        });
        if (saleMode === SALES_TYPE_VALUE.only_store_selling) {
            delete activityInfo.consignment;
        }
        // 删除数据
        delete activityInfo.activityId;
        delete activityInfo.brandId;
        delete activityInfo.storeId;
        delete activityInfo.pubUserId;
        delete activityInfo.qualifyTypes;
        delete activityInfo.processStatus;
        delete activityInfo.published;
        delete activityInfo.verifyQualification;
        delete activityInfo.owner;
        delete activityInfo.pics;
        delete activityInfo.deliveryModes;
        delete activityInfo.unifiedShippingFee;
        delete activityInfo.isUseWarehouseShippingFeeRule;
    } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
        const { activityProductWithSkus } = activityInfo;
        activityInfo = pick(activityInfo, 'endorseActivityId', 'name', 'tel', 'intro', 'background');
        activityInfo.activityProductIsShows = activityProductWithSkus.map(ps => ({
            productId: ps.productId,
            isShow: ps.isShow,
        }));
    }
    return activityInfo;
};

/**
 * 更具活动信息和用户信息，返回相应的操作菜单
 * @param {Object} acivityInfo 活动信息
 * @param {Object} userInfo 用户信息
 * @param {Object} brandInfo 品牌信息
 */
export const getActionMenu = (acivityInfo) => {
    let { type, owner, canManage, saleMode, processStatus, userType } = acivityInfo;
    // userType
    if (!userType) {
        userType = ACTIVITY_USER_ROLE.normal;
        if (owner === ACTIVITY_OWNER_VALUE.brand) {
            canManage && (userType = ACTIVITY_USER_ROLE.owner);
        } else if (owner === ACTIVITY_OWNER_VALUE.store) {
            canManage && (userType = ACTIVITY_USER_ROLE.owner);
        } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
            canManage && (userType = ACTIVITY_USER_ROLE.user);
        }
    }
    let actions = ACTIVITY_ACTION[userType];
    if (type !== ACTIVITY_TYPE.group_buying || saleMode === SALES_TYPE_VALUE.only_brand_selling  || saleMode === SALES_TYPE_VALUE.only_store_selling || processStatus === ACTIVITY_STATUS_VALUE.draft) {
        actions = actions.filter(i => i.action !== USER_ACTION_TYPE.statsConsignmentActivity);
    }
    if (processStatus !== ACTIVITY_STATUS_VALUE.processing && processStatus != ACTIVITY_STATUS_VALUE.paused && processStatus !== ACTIVITY_STATUS_VALUE.starting) {
        actions = actions.filter(i => i.action !== USER_ACTION_TYPE.overOrOpenActivity);
    }
    if (!(processStatus !== ACTIVITY_STATUS_VALUE.finished && processStatus !== ACTIVITY_STATUS_VALUE.closed)) {
        actions = actions.filter(i => i.action !== USER_ACTION_TYPE.changeActivity);
    }
    actions = actions.map(i => {
        if (i.action === USER_ACTION_TYPE.overOrOpenActivity) {
            i.name = processStatus === ACTIVITY_STATUS_VALUE.paused ? '启用活动' : '停用活动';
        }
        return i;
    });
    return actions;
};

/**
 * 处理活动列表数据
 * @param {Array} list 
 */
export const dealActivityListData = (list, ownerInfo) => {
    return list.map(item => {
        ownerInfo && Object.assign(item, ownerInfo);
        let canManage = ownerInfo && ownerInfo.canManage;
        let { type, activityId, brandId, storeId, spokesmanId, name, intro, saleMode, background, processStatus,
            uv, pv, iv, begined, published, modified, owner, ownerId, ownerName,
            ownerPic, hasNotEndorsed = false, pubUserId, timeRanges = [] } = item;
        // ownerId
        if (owner === ACTIVITY_OWNER_VALUE.brand) {
            ownerId = brandId;
        } else if (owner === ACTIVITY_OWNER_VALUE.store) {
            ownerId = storeId;
        } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
            ownerId = spokesmanId;
        }
        // userType
        let userType = ACTIVITY_USER_ROLE.normal;
        if (owner === ACTIVITY_OWNER_VALUE.brand) {
            canManage && (userType = ACTIVITY_USER_ROLE.owner);
        } else if (owner === ACTIVITY_OWNER_VALUE.store) {
            canManage && (userType = ACTIVITY_USER_ROLE.owner);
        } else if (owner === ACTIVITY_OWNER_VALUE.spokesman) {
            canManage && (userType = ACTIVITY_USER_ROLE.user);
        }
        // pics
        let pics = [];
        intro.filter(i => i.type === 'pic' || i.type === 'pic_list')
            .forEach(i => {
                const urls = i.type === 'pic_list' ? i.resource.split(',') : [i.resource];
                pics = pics.concat(urls);
            });
        // 未开始
        let now = Date.now();
        if (processStatus === ACTIVITY_STATUS_VALUE.processing && begined > now) processStatus = ACTIVITY_STATUS_VALUE.starting;
        if (!timeRanges.length) timeRanges = [{ beginAt: '00:00', endAt: '24:00' }];
        return {
            type,
            id: activityId,
            activityId,
            brandId,
            storeId,
            spokesmanId,
            saleMode,
            name,
            uv,
            pv,
            iv,
            dateStr: published ? `${getTimeDuration(published, '前')} 发布` : `${getTimeDuration(modified, '前')} 修改`,
            pics,
            background,
            owner,
            ownerId,
            ownerName,
            ownerPic,
            processStatus,
            canManage,
            hasNotEndorsed,
            pubUserId,
            userType,
            timeRanges,
        };
    })
};

/**
 * 处理活动详情数据
 * @param {Object} activityInfo 
 */
export const dealActivityDetailData = (activityInfo, isCopy) => {
    let { intro, processStatus, begined, activityProductWithAttributeDefAndSkus } = activityInfo;
    // activityProductWithAttributeDefAndSkus
    if (activityProductWithAttributeDefAndSkus && activityProductWithAttributeDefAndSkus.length) {
        activityInfo.activityProductWithAttributeDefAndSkus = activityProductWithAttributeDefAndSkus.filter(i => !!i.isShow);
    }
    // pics
    let pics = [];
    intro.filter(i => i.type === 'pic' || i.type === 'pic_list')
        .forEach(i => {
            const urls = i.type === 'pic_list' ? i.resource.split(',') : [i.resource];
            pics = pics.concat(urls);
        });
    activityInfo.pics = pics;
    // 未开始
    let now = Date.now();
    if (processStatus === ACTIVITY_STATUS_VALUE.processing && begined > now) processStatus = ACTIVITY_STATUS_VALUE.starting;
    activityInfo.processStatus = processStatus;
    // 复制活动
    if (isCopy) {
        if (activityInfo.activityProductWithSkus && activityInfo.activityProductWithSkus.length) {
            activityInfo.activityProductWithSkus = activityInfo.activityProductWithSkus.map(ps => {
                delete ps.activityProductId;
                if (ps.skus && ps.skus.length) {
                    ps.skus = ps.skus.map(s => {
                        delete s.activitySkuId;
                        return s;
                    });
                }
                return ps;
            });
        }
    }
    return activityInfo;
};


/**
 * 处理活动开始时段分组数据
 * @param {Array} list 
 */
export const dealActivityGroupByBeginAtData = (list) => {
    let groups = groupBy(list, (item) => item.timeRanges[0].beginAt);
    return groups.sort((a, b) => a[0].timeRanges[0].beginAt.replace(':', '') - b[0].timeRanges[0].beginAt.replace(':', ''));
};
